<template>
  <div class="wrap">
    <div id="box">
      <div id="marquee">{{ text }}</div>
      <div id="copy"></div>
    </div>
    <div id="node">{{ text }}</div>
  </div>
</template>

<script>
export default {
  props: ['lists'], // 父组件传入数据， 数组形式 [ "连雨不知春去"，"一晴方觉夏深"]
  data() {
    return {
      text: '', // 数组文字转化后的字符串
      intervalId: null // 用于存储 setInterval 的 ID
    }
  },
  methods: {
    move() {
      // 清除之前的 setInterval
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }

      // 获取文字text 的计算后宽度  （由于overflow的存在，直接获取不到，需要独立的node计算）
      let width = document.getElementById('node').getBoundingClientRect().width;
      let box = document.getElementById('box');
      let copy = document.getElementById('copy');
      copy.innerText = this.text; // 文字副本填充
      let distance = 0; // 位移距离

      // 设置位移
      this.intervalId = setInterval(() => {
        distance = distance - 1;
        // 如果位移超过文字宽度，则回到起点
        if (-distance >= width) {
          distance = 16;
        }
        box.style.transform = 'translateX(' + distance + 'px)';
      }, 40);
    },
    updateText() {
      this.text = '';
      for (let i = 0; i < this.lists.length; i++) {
        this.text += ' ' + this.lists[i];
      }
      console.log('updated text:', this.text);
      this.move();
    }
  },
  // 把父组件传入的arr转化成字符串
  mounted() {
    console.log('mounted lists:', this.lists);
    this.updateText();
  },
  updated() {
    this.move()
  },
  watch: {
    lists: {
      handler(newVal) {
        console.log('lists changed:', newVal);
        this.updateText();
      },
      deep: true // 深度监听数组变化
    }
  }
}
</script>

<style scoped>
/*样式的话可以写*/
.wrap {
  overflow: hidden;
  background: white;
}
#box {
  width: 500%;
  display: flex;
  align-items: center;
}
#box div {
  float: left;
}
#copy{
  color:cornflowerblue;
}
#marquee {
  margin: 0 16px 0 0;
  color:cornflowerblue;
}
#node {
  position: absolute;
  z-index: -99;
  top: -99px;
  color:cornflowerblue;
}
</style>
